#!/usr/bin/env python
#-*- coding:utf-8 -*-

# file:readerController.py
# author:ytytyt
# datetime:2021/6/26 17:50
# software: PyCharm
"""
this is functiondescription
"""
# import module your need
from app import db

from models.readerModel import ReaderModel
from utils import commons
from utils.response_code import RET
from flask import current_app,jsonify

#实体类控制类，用于实现专门对实体类的操作（增删改查）
#目前还没完成，仅测试用
class ReaderController(ReaderModel):

    # 增
    @classmethod
    def add(cls, **kwargs):
        try:
            if cls.get_by_name(**kwargs).get('code')==RET.DATAEXIST:
                return {
                    'code': RET.DATAEXIST,
                    'message': '添加失败',
                }
            reader_info = ReaderModel(name=kwargs.get('name'),
                                   password=kwargs.get('password'),
                                   sex=kwargs.get('sex'),
                                   )

            db.session.add(reader_info)
            print("添加成功")
            db.session.flush()
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, message='数据库异常，添加失败', error=str(e))

        #得到的结果转为字典
        results = commons.query_to_dict(reader_info)
        db.session.close()
        # 要返回的信息，直接返回json格式
        # return jsonify(code=RET.OK, message='添加成功', data=results)

        # 要返回的信息--直接返回字典数据类型方便接口层处理
        res_dict = {
            'code': RET.OK,
            'message': '添加成功',
            'data': results
        }
        return res_dict

    # 删
    # @classmethod
    # def delete(cls, **kwargs):
    #
    #     try:
    #         toDoList = db.session.query(cls).filter(cls.AutoID == kwargs.get("AutoID")).filter(
    #             cls.IsDelete == 0).first()
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return {'code': RET.DBERR, 'message': '数据库异常，信息查询失败', 'error': str(e)}
    #     if not toDoList:
    #         return {'code': RET.NODATA, 'message': '无事项信息', 'error': '无事项信息'}
    #     try:
    #         toDoList.IsDelete = 1
    #         db.session.commit()
    #         return jsonify(code=RET.OK, message='删除成功')
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         db.session.rollback()
    #         return {'code': RET.DBERR, 'message': '数据库异常，删除失败', 'error': str(e)}
    #     finally:
    #         db.session.close()

    # 改
    # @classmethod
    # def put(cls, **kwargs):
    #     # 先判断要修改的记录是否存在
    #     try:
    #         # 过滤为空的查询参数
    #         toDoList = db.session.query(cls).filter(and_(cls.AutoID == kwargs.get("AutoID")), cls.IsDelete == 0)
    #         if not toDoList.first():
    #             return {'code': RET.NODATA, 'message': '没有要更新的记录', 'error': '无待更新的数据'}
    #
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return {'code': RET.DBERR, 'message': '数据库异常获取信息失败', 'error': str(e)}
    #     try:
    #         # 准备更新数据
    #         toDoList.update(kwargs)
    #         db.session.commit()
    #         return {'code': RET.OK, 'message': '修改成功'}
    #     except Exception as e:
    #         db.session.rollback()
    #         current_app.logger.error(e)
    #         return {'code': RET.DBERR, 'message': '数据异常，修改失败', 'error': str(e)}
    #     finally:
    #         db.session.close()

    # 查--根据ID(标准查询)
    @classmethod
    def get(cls, **kwargs):
        try:
            reader_info = db.session.query(cls).filter(db.and_(cls.name==kwargs.get('name'),cls.password==kwargs.get('password') )).first()
            print(kwargs.get('name'))
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}
        finally:
            db.session.close()
        if not reader_info:
            return {'code': RET.NODATA, 'message': '无读者信息', 'error': '无读者信息'}

        # 处理返回的数据
        results = commons.query_to_dict(reader_info)
        res_dict = {
            'code': RET.OK,
            'message': '查询成功',
            'data': results
        }
        return res_dict

    @classmethod
    def get_by_name(cls, **kwargs):
        try:
            reader_info = db.session.query(cls).filter(
               cls.name == kwargs.get('name')).first()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}
        finally:
            db.session.close()
        if not reader_info:
            return {'code': RET.NODATA}

        # 处理返回的数据

        return {'code': RET.DATAEXIST}